<script setup lang="ts">
import Tools from '@/utils/tools';
import ButtonTemplate from '@/pages/home/component/template/ButtonTemplate.vue';
import BannerTemplate from '@/pages/home/component/template/BannerTemplate.vue';
import RecommendTemplate from '@/pages/home/component/template/RecommendTemplate.vue';
import ProductListTemplate from '@/pages/home/component/template/ProductListTemplate.vue';
import EventCollection from '@/pages/home/eventCollection';
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import useModal from '@/hooks/useModal';

interface IProps {
  serverList?: IServerBtnListRes;
  btnModelRelations: BtnModelRelations[];
}

interface IState {
  template: BtnModelRelations[];
  searchText: string;
  rescueInformation?: IObtainRecentFirstAidOrderRes;
}

const store = useAppStore();
const { showModal } = useModal();
const props = defineProps<IProps>();
const state = reactive<IState>({ template: [], searchText: '' });

onMounted(() => {
  handleMatchTemplateWithButtons(props.btnModelRelations);
});

watch(
  () => props.btnModelRelations,
  (btnModelRelations) => {
    handleMatchTemplateWithButtons(btnModelRelations);
  },
);

// 将模版与按键匹配
const handleMatchTemplateWithButtons = (btnModelRelations: BtnModelRelations[]) => {
  if (props.serverList && btnModelRelations.length > 0) {
    const _btnModelRelations: BtnModelRelations[] = JSON.parse(JSON.stringify(btnModelRelations));
    if (btnModelRelations[0].moduleType === 5) {
      const [_first, ...rest] = _btnModelRelations;
      state.template = handleTemplateMatching(rest);
    } else {
      state.template = handleTemplateMatching(btnModelRelations);
    }
  }
};

// 模版匹配按钮
const handleTemplateMatching = (btnModelRelations: BtnModelRelations[]) => {
  let _btnModelRelations = Tools.deepClone(btnModelRelations);
  const filterBtnList = props.serverList!.btnList.filter((item) => !item.parentBtnCode);
  _btnModelRelations.forEach((item) => {
    if (item.moduleType == 1 && item.btnFormats.length > 0) {
      item.btnFormats.forEach((item2) => {
        item2.list = Tools.convertOneDToTwoD(
          filterBtnList.filter((item3) => item3.formatCode === item2.formatCode && item3.moduleCode === item.moduleCode),
          item2.row * item2.col,
        );
        item2.currentIndex = 0;
      });
    }
    if (item.moduleType === 2) {
      item.banner = filterBtnList.filter((item2) => item2.moduleCode === item.moduleCode);
    }
    if (item.moduleType === 3) {
      item.recommend = Tools.convertOneDToTwoD(
        filterBtnList.filter((item2) => item2.moduleCode === item.moduleCode),
        3,
      );
    }
    if (item.moduleType === 4) {
      item.productList = filterBtnList.find((item2) => item2.moduleCode == item.moduleCode);
    }
    if (item.moduleType === 6) {
      item.searchCorrBtn = filterBtnList.find((item2) => item2.btnModuleType == 6);
    }
    if (item.moduleType === 7 && filterBtnList.some((item2) => item2.btnModuleType === 7)) {
      fetchRecentFirstAidOrderData(filterBtnList.find((item2) => item2.btnModuleType === 7)!.id);
    }
  });
  //  搜索模块 推荐模块、产品模块没有对应按键 模版中不渲染
  [6, 3, 4].forEach((item) => {
    if (!props.serverList?.btnList.find((c) => c.btnModuleType === item)) {
      _btnModelRelations = _btnModelRelations.filter((c) => c.moduleType !== item);
    }
  });

  // 剔除空数据的banner模块
  _btnModelRelations = _btnModelRelations.filter((item) => !(item.moduleType === 2 && item.banner.length === 0));
  return _btnModelRelations;
};

// 请求急救信息
const fetchRecentFirstAidOrderData = (btnId: number) => {
  HomeRequest.ObtainRecentFirstAidOrder({ btnId, beeperId: store.$state.beeperId }).then((res) => {
    state.rescueInformation = res.data;
  });
};

// 急救模块图片预览
const handleFirstAidModuleImagePreview = () => {
  if (state.rescueInformation && state.rescueInformation.siteUrl) {
    uni.previewImage({
      current: state.rescueInformation.siteUrl,
      urls: [state.rescueInformation.siteUrl],
    });
  }
};

const handleNotificationClick = () => {
  if (state.rescueInformation) {
    showModal(`${state.rescueInformation.villageName}${state.rescueInformation.floorName}${state.rescueInformation.houseNumber}出现急救情况`, undefined, '急救通知');
  }
};
</script>

<template>
  <view class="mx-[12px] mt-[12px] c-br bg-white mb-[12px] overflow-hidden" v-for="(item, index) in state.template" :key="index">
    <!--  左上角图标   -->
    <image v-if="item.tagUrl" class="w-full h-[35px]" mode="widthFix" lazy-load :src="item.tagUrl" />
    <!--  按键模版   -->
    <ButtonTemplate v-if="item.moduleType === 1 && item.btnFormats.length > 0" :data="item" :btn-list="props.serverList!.btnList" />
    <!--  banner模版   -->
    <BannerTemplate v-if="item.moduleType === 2 && item.banner && item.banner.length > 0" :item="item" :data="item.banner" />
    <!--  推荐模版   -->
    <RecommendTemplate v-if="item.moduleType === 3 && item.recommend && item.recommend.length > 0" :data="item.recommend" />
    <!--  首页产品列表模块   -->
    <ProductListTemplate v-if="item.moduleType === 4 && item.productList" :data="item.productList" :title="item.listTitle" :styleType="item.styleType" />
    <!--  大图模块   -->
    <view v-if="item.moduleType === 5 && index !== 0" class="h-[140px] c-br overflow-hidden">
      <van-image width="100%" height="100%" fit="cover" :src="item.bigImgUrl" />
    </view>
    <!--  搜索模块   -->
    <van-search v-if="item.moduleType === 6" :value="state.searchText" shape="round" input-align="center" placeholder="请输入搜索关键词" @change="(e: any) => (state.searchText = e.detail)" @search="EventCollection.onPress(item.searchCorrBtn, 6, undefined, state.searchText)" />
    <!--  动态信息模块   -->
    <view v-if="item.moduleType === 7 && state.rescueInformation" class="p-8px pt-0 box-border">
      <van-notice-bar left-icon="volume-o" color="red" background="white" :text="state.rescueInformation.villageName + state.rescueInformation.floorName + state.rescueInformation.houseNumber + '出现急救情况'" @click="handleNotificationClick" />
      <image class="w-full h-230px c-br" :src="state.rescueInformation.siteUrl" mode="aspectFill" @click="handleFirstAidModuleImagePreview" />
      <view class="flex justify-between c-text-12 mt-8px">
        <view>
          <text class="mr-4px color-red">{{ state.rescueInformation.twoTaskJobType }}</text>
          人正前往急救
        </view>
        <view>
          <text class="mr-4px color-red">{{ state.rescueInformation.oneTaskJobType }}</text>
          人正前往取AED
        </view>
      </view>
    </view>
  </view>
</template>
